import { ref, nextTick } from 'vue'
import { regExp } from '@/utils/regExp'
import { loginByPassword, loginByCaptcha } from '@/api'
import { useLocationStore } from '@/store/location'
import { useUserStore } from '@/store/user'
import { startConnect } from '@/tcpSocket'

export function useLogin() {
  const userStore = useUserStore()
  const locationStore = useLocationStore()
  const currentAction = ref('login')
  const password = ref('')
  const loginWay = ref('password')
  const triangleOffset = ref(0)
  const loginOptions = [
    { code: 'password', name: '密码登录' },
    { code: 'captcha', name: '验证码登录' }
  ]

  /**
   * 切换登录方式
   * @param {'password' | 'captcha'} way 登录方式
   */
  function setLoginWay(way) {
    loginWay.value = way
    nextTick(getTriangleOffset)
  }

  function getTriangleOffset() {
    uni
      .createSelectorQuery()
      .select('.toggle-item.checked')
      .boundingClientRect(
        res => (triangleOffset.value = res.left + res.width / 2)
      )
      .exec()
  }

  /**
   * 密码登录或者验证码登录
   * @param {string} phoneNumber 手机号
   * @param {string} captcha 验证码
   */
  function handleLogin(phoneNumber, captcha) {
    console.log(phoneNumber)
    const showMsg = title => uni.showToast({ title, icon: 'none' })
    if (!regExp.phoneNumber.test(phoneNumber))
      return showMsg('手机号码输入不正确')

    const params = {
      phone: phoneNumber,
      latitude: locationStore.latitude,
      longitude: locationStore.longitude
    }
    const action = {
      password: () => {
        if (!password.value) return showMsg('还没有输入密码')
        params['password'] = password.value
        loginByPassword(params).then(res => {
          userStore.login(res)
          startConnect()
        })
      },
      captcha: () => {
        if (!captcha) return showMsg('还没有输入验证码')
        params['code'] = captcha
        loginByCaptcha(params).then(res => {
          userStore.login(res)
          startConnect()
        })
      }
    }

    action[loginWay.value]()
  }

  return {
    currentAction,
    loginWay,
    password,
    triangleOffset,
    loginOptions,
    setLoginWay,
    getTriangleOffset,
    handleLogin
  }
}
